<template>
  <div>
    <el-menu :default-active="activeIndex" class="el-menu-demo" mode="horizontal" @select="handleSelect">
      <div style="display: flex; justify-content: center; align-items: center;">
        <!-- 网站图标 -->
        <el-menu-item style="width: 300px; pointer-events: none; color: inherit;" @click="preventClick">
          <img style="width: 50px; height: auto; margin-right: 6px;" src="../assets/xh.png" alt="校徽">
          <span style="font-family: '隶书'; font-size: 18px;">中山大学</span>
          <span style="margin: 0 5px;"> | </span>
          <span style="font-family: '方正舒体'; font-size: 18px;">数字百团</span>
        </el-menu-item>
<!--        用户-->
        <div v-if="activeNavbar==='user' " style="display: flex;">
          <el-menu-item @click="goToPage('/home')" index="1" style="font-size: 16px;">首页</el-menu-item>
          <el-menu-item @click="goToPage('/club')" index="2" style="font-size: 16px;">社团</el-menu-item>
          <el-menu-item @click="goToPage('/activity')" index="3" style="font-size: 16px;">活动</el-menu-item>
        </div>
<!--        社团负责人-->
        <div v-if="activeNavbar==='admin' " style="display: flex;">
          <el-menu-item @click="goToPage('/clubManage')" index="1" style="font-size: 16px;" >社团</el-menu-item>
          <el-menu-item @click="goToPage('/ActManage')" index="2" style="font-size: 16px;">活动</el-menu-item>
          <el-menu-item @click="goToPage('/approval1')" index="3" style="font-size: 16px;">审批</el-menu-item>
          <el-menu-item @click="goToPage('/ASCEManage')" index="4" style="font-size: 16px;">年检评优</el-menu-item>
          <el-menu-item @click="goToPage('/noticemanage')" index="5" style="font-size: 16px;">公告</el-menu-item>
        </div>
<!--        学院-->
        <div v-if="activeNavbar==='academy' " style="display: flex;">
          <el-menu-item @click="goToPage('/clubManage')" index="1" style="font-size: 16px;">社团</el-menu-item>
          <el-menu-item @click="goToPage('/ActManage')" index="2" style="font-size: 16px;">活动</el-menu-item>
          <el-menu-item @click="goToPage('/approval2')" index="3"  style="font-size: 16px;">审批</el-menu-item>
          <el-menu-item @click="goToPage('/noticemanage')" index="4" style="font-size: 16px;">公告</el-menu-item>
        </div>
<!--        校团委-->
        <div v-if="activeNavbar === 'all'" style="display: flex;">
          <el-menu-item @click="goToPage('/clubManage')" index="1" style="font-size: 16px;">社团</el-menu-item>
          <el-menu-item @click="goToPage('/ActManage')" index="2" style="font-size: 16px;">活动</el-menu-item>
          <el-menu-item @click="goToPage('/approval2')" index="3" style="font-size: 16px;">审批</el-menu-item>
          <el-menu-item @click="goToPage('/ACManage')" index="4" style="font-size: 16px;">年检评优</el-menu-item>
          <el-menu-item @click="goToPage('/noticemanage')" index="5" style="font-size: 16px;">公告</el-menu-item>
          <el-menu-item @click="goToPage('/statistics')" index="6" style="font-size: 16px;">数据统计</el-menu-item>
        </div>

      </div>

      <div style="display: flex;align-items: center;">
        <!-- 切换按钮-->
        <div v-if="activeNavbar==='user' ">
          <el-menu-item class="switch_item">
            <el-button plain class="switch_btn" @click="user_toggleNavbar()"><el-icon color="#777575" class="no-inherit"><Switch /></el-icon>切换管理员端</el-button>
          </el-menu-item>
        </div>
        <div v-else>
          <el-menu-item class="switch_item">
            <el-button plain class="switch_btn" @click="admin_toggleNavbar()"><el-icon color="#777575" class="no-inherit"><Switch /></el-icon>切换用户端</el-button>
          </el-menu-item>
        </div>

        <!-- 消息按钮 -->
        <el-menu-item>
          <el-popover placement="bottom" :width="250" trigger="click">
            <template #reference>
              <button plain class="message-btn" @click="fetchMessages">
                <el-badge :value="this.$store.state.userinfo.unread" :max="99" class="item">
                  <el-icon color="red" class="no-inherit" :size="20" style="vertical-align: middle">
                    <Bell />
                  </el-icon>
                </el-badge>
                <div>消息</div>
              </button>
            </template>
            <div v-if="this.$store.state.userinfo.unread === 0">暂时没有未读消息</div>
            <div v-else style="display:flex;flex-direction: column;">
              <div v-for="type in categorizedMessages" :key="type.type">
                <div v-if="type.unread_count>0" style="display: flex;padding: 10px;cursor: pointer;border-bottom: 1px solid #eee;">
                  <div :style="{ backgroundImage: 'url(' + type.avatar + ')' }"
                       style="width: 50px;
                       height: 50px;
                       background-size: cover;
                       border-radius: 50%;
                       margin-right: 10px;"></div>
                  <div class="name-box">
                    <div class="name">
                      <div class="name-value">{{ type.type_name }}</div>
                    </div>
                    <div class="last-word">
                      <span v-if="type.unread_count > 0">[未读] {{ type.unread_count }} 条消息</span>
                    </div>
                  </div>
                </div>
              </div>
              <el-button type="text" @click="showAllMessages">显示全部消息</el-button>
            </div>
          </el-popover>
        </el-menu-item>

        <!-- 头像下拉框 -->
        <el-menu-item class="profile">
          <el-dropdown trigger="hover" placement="bottom" class="profile_dropdown">
            <div style="flex:1;display: flex;align-items: center;" class="pdt">
              <img :src="avatar"   alt="some_text"    style="border-radius: 0;width: 60px;height: 50px;cursor: pointer;object-fit: cover;" />
              <span style="margin-left: 10px;margin-right: 30px;font-family: 'Arial';font-size: 16px;color: black;">{{username}}</span>
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="goToPage('/personalcenter')">个人中心</el-dropdown-item>
                <el-dropdown-item  @click="showChangePasswordDialog">修改密码</el-dropdown-item>
                <el-dropdown-item @click="handleLogout">退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </el-menu-item>

        <el-dialog v-model="DialogVisible" title="修改密码" style="width: 450px;" @close="handleClose">
          <el-form
              :model="changePasswordForm"
              :rules="changePasswordRules"
              ref="changePasswordForm"
              label-width="100px"
              style="width: 400px;">
            <el-form-item label="当前密码" prop="currentPassword">
              <el-input v-model="changePasswordForm.currentPassword" type="password"></el-input>
            </el-form-item>
            <el-form-item label="新密码" prop="newPassword">
              <el-input v-model="changePasswordForm.newPassword" type="password"></el-input>
              <span style="color: gray; font-size: 12px;">密码长度不能少于6位，必须包含字母和数字</span>
            </el-form-item>
            <el-form-item label="确认新密码" prop="confirmNewPassword">
              <el-input v-model="changePasswordForm.confirmNewPassword" type="password"></el-input>
            </el-form-item>
          </el-form>
          <template  #footer>
            <div class="dialog-footer">
              <el-button @click="handleCancel">取消</el-button>
              <el-button type="primary" @click="handleChangePassword">确认</el-button>
            </div>
          </template>

        </el-dialog>
      </div>
    </el-menu>
  </div>
</template>

<script>
import axios from "axios";
import {ElMessage} from "element-plus";
import { mapState, mapActions } from 'vuex';
export default {
  data() {
    return {
      activeNavbar: 'user',
      username: this.$store.state.userinfo.username,
      avatar:this.$store.state.userinfo.avatar.url,
      
      categorizedMessages:[],
      DialogVisible: false,
      changePasswordForm: {
        currentPassword: '',
        newPassword: '',
        confirmNewPassword: ''
      },
      changePasswordRules: {
        currentPassword: [{ required: true, message: '请输入当前密码', trigger: 'blur' }],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, message: '新密码长度不能少于6位', trigger: 'blur' },
          {
            pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,}$/,
            message: '新密码必须包含字母和数字',
            trigger: 'blur'
          }
        ],
        confirmNewPassword: [
          { required: true, message: '请确认新密码', trigger: 'blur' },
          { validator: (rule, value, callback) => {
              if (value !== this.changePasswordForm.newPassword) {
                callback(new Error('两次输入的新密码不一致'));
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }
        ]}
    };
  },
  methods: {
    ...mapActions(['setIndex']),
    user_toggleNavbar() {
      if(this.$store.state.userinfo.permission==0){
        ElMessage.error("您暂时不是管理员！")
      }
      if(this.$store.state.userinfo.permission==1){
        this.activeNavbar = 'admin';
        this.$router.push('/clubManage');
        this.setIndex("1")
      }
      else if(this.$store.state.userinfo.permission==2){
        this.activeNavbar = 'academy';
        this.$router.push('/clubManage');
        this.setIndex("1")
      }
      else if(this.$store.state.userinfo.permission==3) {
        this.activeNavbar = 'all';
        this.$router.push('/clubManage');
        this.setIndex("1")
      }
    },
    admin_toggleNavbar() {
      this.activeNavbar = 'user';
      this.$router.push('/home');
    },
    async handleLogout(){
      localStorage.removeItem('token');
      window.location.href = '/login';
    },
    showChangePasswordDialog() {
      this.DialogVisible = true;
    },
    handleCancel() {
      console.log("handcancel")
      this.DialogVisible = false;
      this.resetForm();
    },
    handleClose() {
      console.log("handclose")
      this.resetForm();
    },
    resetForm() {
      console.log("restewvvvvvvvvrbgocebi")
      this.changePasswordForm.currentPassword = '';
      this.changePasswordForm.newPassword = '';
      this.changePasswordForm.confirmNewPassword = '';
      this.$nextTick(() => {
        this.$refs.changePasswordForm.resetFields()
      });
    },
    async handleChangePassword() {
      this.$refs.changePasswordForm.validate(async (valid) => {
        if (valid) {
          const formData = new FormData()
          formData.append("uid",this.$store.state.userinfo.account)
          formData.append("currentPassword", this.changePasswordForm.currentPassword,)
          formData.append("newPassword", this.changePasswordForm.newPassword)
          // 提交修改密码请求
          try {
            const response = await axios.post('/api/changePassword', formData);
            if ((response.status=="200")) {
              ElMessage.success('密码修改成功');
              this.$store.dispatch('savePassword', this.changePasswordForm.newPassword);
              this.resetForm();
              this.DialogVisible = false;

            } else {
              ElMessage.error('密码修改失败');
            }
          } catch (error) {
            ElMessage.error('密码修改失败');
          }
        }
      });
    },
    async fetchMessages() {
      axios.get('/api/msg', {
        params: {
          account: this.$store.state.userinfo.account
        }
      })
          .then(response => {
            if(response.data.data.messages){
              console.log("导航栏消息：",response)
              this.categorizedMessages = response.data.data.messages;
            }
          })
          .catch(function (err) {
            ElMessage.error('获取消息失败');
            console.log('消息获取失败' + err)
          })
    },
    formatDate(dateString) {
      const date = new Date(dateString);
      const year = date.getUTCFullYear();
      const month = date.getUTCMonth() + 1;
      const day = date.getUTCDate();
      const hours = date.getUTCHours();
      const minutes = date.getUTCMinutes();
      return `${year}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day} ${hours < 10 ? '0' + hours : hours}:${minutes < 10 ? '0' + minutes : minutes}`;
    },
    goToPage(route) {
      this.$router.push(route);
      this.setIndex('');
    }
  },
  computed: {
   ...mapState(['activeIndex']),
 
  },
  mounted() {
    this.fetchMessages();
  }
}
</script>

<style scoped lang="scss">
.el-menu-demo {
  background-color: #DFF3FF;
  position: fixed;
  top: 0;
  width: 100%;
  display: flex;
  height:65px;
  justify-content: space-between;

  .switch_item {
    background-color: transparent !important;
    border-color: transparent !important;
    .switch_btn {
      background-color: transparent !important;
      border: none;
    }
  }

  .message-btn {
    background-color: transparent !important;
    border: none;
  }

  .profile {
    .profile_dropdown {
      .pdt {
        outline: none;
      }
    }

  }
  .list-item {
    display: flex;
    padding: 10px;
    cursor: pointer;
    border-bottom: 1px solid #eee;
  }
  .name-box {
    flex: 1;
  }

  .name-value {
    font-weight: bold;
  }

  .last-word {
    color: #888;
  }
}
</style>


